import json
import logging
import time

import requests

from Spider.api import TuShareAPI
from Spider.config import CONFIG, G
from Spider.tool import cal_run_time

G_MESSAGE_QUEUE = None
CONVBOND_STATE_MAP = {
    -1: "异常",
    0: "持有可转债",
    1: "买入可转债A",
    2: "买入可转债B"
}


def get_convbonds():
    """

    获取所有债券信息

    :return:
    """
    response = requests.get("{}/index/api/convbond/".format(CONFIG.LOCAL_URL))
    convbonds = json.loads(response.text)
    return convbonds


def get_details(convbonds):
    """
    监控两只债券 a,b

    获取 买1卖1还有成交量

    港股为116.0 + 4位股票代号
    A股为 1. + 6位A股代码
    基金为0. + 基金代号


    :param code:
    :return:
    """
    a_code = convbonds[0]["cb_code"]
    a_name = convbonds[0]["cb_name"]
    b_code = convbonds[1]["cb_code"]
    b_name = convbonds[1]["cb_name"]
    result = {
        "a_code": a_code,
        "a_name": a_name,
        "b_code": b_code,
        "b_name": b_name
    }
    state_in_database = convbonds[0]["cb_flag"]
    # https://push2his.eastmoney.com/api/qt/stock/trends2/get?secid=1.110063&fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14&fields2=f51,f53,f54,f55,f56,f57,f58&iscr=0
    time, buy1s, sell1s = TuShareAPI.get_some_buy1_sell1([a_code, b_code])
    a_buy_1, b_buy_1 = buy1s[0], buy1s[1]
    a_sell_1, b_sell_1 = sell1s[0], sell1s[1]

    # 如果a卖1大于b买1 1% 可转债b
    # %1到-1% 可持债
    # -1%小于 可转债务a
    a_sell_1 = float(a_sell_1)
    b_buy_1 = float(b_buy_1)
    asell_bbuy1_rate = round((a_sell_1 - b_buy_1) / b_buy_1 * 100, 2)
    if asell_bbuy1_rate > 1:
        state = 2  # 买入可转债b
    elif asell_bbuy1_rate < -1:
        state = 1  # 买入可转债a
    else:
        state = 0  # 持可转债
    try:
        if state_in_database != state:
            requests.patch("{}/index/api/convbond/{}/".format(CONFIG.LOCAL_URL, a_code),
                           data={"cb_flag": state})
            G.MESSAGE_QUEUE_LOCK.acquire()
            text = "可转债状态由{}变更为{}".format(CONVBOND_STATE_MAP[state_in_database], CONVBOND_STATE_MAP[state])
            print("发送微信：" + text)
            global G_MESSAGE_QUEUE
            G_MESSAGE_QUEUE.put(text)
            G.MESSAGE_QUEUE_LOCK.release()
    except Exception as e:
        print("更新状态失败,{}".format(e.args))
        state = -1

    asell_bbuy1_rate_str = str(asell_bbuy1_rate) + '%'

    result.update(
        {
            "time": time,
            "abuy1": a_buy_1,
            "asell1": a_sell_1,
            "bbuy1": b_buy_1,
            "bsell1": b_sell_1,
            "as_bb": asell_bbuy1_rate_str,  # a买1比b卖1
            "state": CONVBOND_STATE_MAP[state]
        }
    )
    return [result]  # 转换为list


@cal_run_time(cal_func_place="可转债")
def refresh_data():
    convbonds = get_convbonds()
    result = get_details(convbonds)
    return result


def run(MESSAGE_QUEUE):
    global G_MESSAGE_QUEUE
    G_MESSAGE_QUEUE = MESSAGE_QUEUE
    time.sleep(0.5)
    while True:
        result = refresh_data()
        # print("获取转债数据：", result)
        try:
            requests.post("{}/index/post/convbond/".format(CONFIG.LOCAL_URL), data={'data': json.dumps(result)})
        except Exception as e:
            logging.error("债券获取上传出错")
            print(e)
        time.sleep(CONFIG.CONVBOND_BACKENDCIRCLE)
